package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Utils.DateUtils;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    /**
     * 页面右上角显示用户名
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {

            return userDao.findByUsername(username);

    }
    /**
     * 权限管理中用户管理分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        List<User> rows = userDao.selectByCondition(queryString);
        List<Map<String,Object>> maps = new ArrayList<>();
        for (User row : rows) {
            Date birthday = row.getBirthday();
            String s = DateUtils.parseDate2String(birthday, "yyyy-MM-dd");
            Map<String, Object> map = new HashMap<>();
            map.put("id",row.getId());
            map.put("birthday",s);
            map.put("gender",row.getGender());
            map.put("username",row.getUsername());
            map.put("password",row.getPassword());
            map.put("remark",row.getRemark());
            map.put("station",row.getStation());
            map.put("telephone",row.getTelephone());
            maps.add(map);
        }
        return new PageResult((long) rows.size(), maps);
    }

    /**
     * 通过传过来的userId查询绑定的角色
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    /**
     * 通过传过来的角色Id数组,绑定user的角色
     *
     * @param roleIds
     */
    @Override
    public void addRole(User user, Integer[] roleIds) {
        Integer userId = user.getId();
        //判断传过来的roleIds是否有数据
        if (roleIds.length > 0) {
            List<Integer> roleIdsByUserId = userDao.findRoleIdsByUserId(userId);
            //判断该用户是否绑定了角色,如果有绑定,找到没有绑定的角色,并添加
            //没有绑定直接添加
            if (roleIdsByUserId.size() > 0) {
                //想了想, 还是直接删除原有的关联, 然后再重新关联
                //删除关联关系
                userDao.deleteAssociation(userId);
                //添加关联关系
                for (Integer roleId : roleIds) {
                    userDao.addRole(userId, roleId);
                }
            } else {
                for (Integer roleId : roleIds) {
                    userDao.addRole(userId, roleId);
                }
            }
        }else {
            userDao.deleteAssociation(userId);
        }
        String password = user.getPassword();
        Integer userId1 = user.getId();
        User byId = userDao.findById(userId);
        //判断初始密码是否为空
        if(byId.getPassword()==null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encode = encoder.encode(password);
            user.setPassword(encode);
            userDao.update(user);
        }else {
            if(byId.getPassword().equals(password)){
                //密码无变化
                userDao.update(user);
            }else {
                //密码有变化
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                String encode = encoder.encode(password);
                user.setPassword(encode);
                userDao.update(user);
            }
        }


    }

    /**
     * 通过userId查询用户对象
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    /**
     * 用户新建,绑定关联角色,以及判断用户名是否被使用
     * @param user
     * @param roleIds
     * @throws Exception
     */
    @Override
    public void add(User user, Integer[] roleIds) throws Exception{
        String username = user.getUsername();
        User user1 = userDao.findByUsername(username);
        //判断用户名是否被使用
        if(user1 == null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = user.getPassword();
            String encode = encoder.encode(password);
            user.setPassword(encode);
            Date birthday = user.getBirthday();
            String birthday1 = DateUtils.parseDate2String(birthday, "yyyy-MM-dd");
            Date birthday2 = DateUtils.parseString2Date(birthday1);
            user.setBirthday(birthday2);
            userDao.add(user);
            User user2 = userDao.findByUsername(username);
            Integer userId = user2.getId();

            for (Integer roleId : roleIds) {
                userDao.addRole(userId,roleId);
            }
        }else {
            throw new RuntimeException("用户名已被使用!");
        }
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deletebyid(Integer id) {
        userDao.deleteAssociation(id);
        userDao.deletebyid(id);
    }
}
